/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 21:09:40
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-08-27 22:31:29
 */

import {
  contractPage,
  getContractList,
  contractDetail,
  contractAddOrEdit,
} from 'services/contract';

export default {
  namespace: 'contractList',
  state: {
    data: {
      list: [],
      pagination: {},
    },
    list: [],
    detailData: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(contractPage, payload);
      yield put({
        type: 'saveContractList',
        payload: response,
      });
    },
    *getList({ payload }, { call, put }) {
      const response = yield call(getContractList, payload);
      yield put({
        type: 'saveList',
        payload: response,
      });
    },
    *contractDetail({ payload }, { call, put }) {
      const response = yield call(contractDetail, payload);
      yield put({
        type: 'saveContractDetail',
        payload: response,
      });
    },

    *contractAddOrEdit({ payload, callback }, { call, put }) {
      const response = yield call(contractAddOrEdit, payload);
      callback(response);
    },
  },

  reducers: {
    saveContractList(state, action) {
      const {
        data: { contractList, pageIndex, pageSize, recordCount },
      } = action.payload;

      const newList = contractList.map(val => {
        const v = val;
        v.key = `k${v.id}`;
        return v;
      });
      return {
        ...state,
        data: {
          list: newList,
          pagination: {
            current: pageIndex,
            total: recordCount,
            pageSize,
          },
        },
      };
    },
    saveList(state, action) {
      const { data } = action.payload;

      if (!(data instanceof Array)) {
        return {
          ...state,
        };
      }

      const newList = data.map(val => {
        const v = val;
        v.key = `k${v.id}`;
        return v;
      });
      return {
        ...state,
        list: newList,
      };
    },

    saveContractDetail(state, action) {
      const { data } = action.payload;
      return {
        ...state,
        detailData: data,
      };
    },
  },
};
